# coding: utf-8

# -------------------------------------------------------------------------------
# Name:         redis_client.py
# Description:
# Author:       XiangjunZhao
# EMAIL:        2419352654@qq.com
# Date:         2021/8/16 17:31
# -------------------------------------------------------------------------------
import logging

import redis
from sshtunnel import SSHTunnelForwarder

logger = logging.getLogger(__name__)


class RedisClient(object):
    """
    Redis客户端
    """

    def __init__(self, host=None, port=6379, password=None, db=0, ssh_host=None, ssh_username=None, ssh_password=None,
                 use_ssh_tunnel=False):
        """
        数据库工具类初始化方法
        Args:
            host: 数据库地址
            port: 数据库端口
            password: 数据库密码
            db: 数据库
            ssh_host: ssh地址
            ssh_username: ssh用户名
            ssh_password: ssh密码
            use_ssh_tunnel: 使用ssh隧道
        """
        self.host = host
        self.port = port
        self.password = password
        self.db = db
        self.ssh_host = ssh_host
        self.ssh_username = ssh_username
        self.ssh_password = ssh_password
        self.use_ssh_tunnel = use_ssh_tunnel
        self.tunnel = None
        try:
            if self.use_ssh_tunnel:
                self.tunnel = SSHTunnelForwarder(
                    ssh_address_or_host=(self.ssh_host, 22),
                    ssh_username=self.ssh_username,
                    ssh_password=self.ssh_password,
                    remote_bind_address=(self.host, self.port))
                self.tunnel.start()
                self.redis_client = redis.Redis(host='127.0.0.1', port=self.tunnel.local_bind_port, db=self.db,
                                                decode_responses=True, password=self.password)
            else:
                self.redis_client = redis.Redis(host=self.host, port=self.port, db=self.db, password=self.password)
        except Exception as e:
            if self.tunnel:
                self.tunnel.close()
            logger.error(f'Redis数据库工具初始化异常，原因：{e}')

    def get(self, name):
        """

        Args:
            name:

        Returns:

        """
        value = None
        try:
            value = self.redis_client.get(name=name)
            if isinstance(value, bytes):
                value = value.decode(encoding='utf-8')
        except Exception as e:
            logger.error(f'获取数据异常，原因：{e}')
        finally:
            self.close()
        return value

    def close(self):
        self.redis_client.close()
        if self.tunnel:
            self.tunnel.close()
